﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace DreamCMS.WebCore.Common
{
    public class ServerHelper
    {
        private static string preFix = ConfigHelper.SitePrefix;
        /// <summary>
        /// 获取或设置服务端Session保存的验证码
        /// </summary>
        public static string VerifyCode
        {
            get
            {
                return Convert.ToString(HttpContext.Current.Session[preFix + "VerifyCode"]);
            }
            set
            {
                HttpContext.Current.Session[preFix + "VerifyCode"] = value;
            }
        }
        /// <summary>
        /// 当前请求所针对的服务器IP地址
        /// </summary>
        public static string ServerIP
        {
            get
            {
                return HttpContext.Current.Request.ServerVariables["LOCAl_ADDR"];
            }
        }

        /// <summary>
        /// 提供cookie名，cookie值和过期时间来设置客户端的cookie
        /// </summary>
        /// <param name="cookieName">cookie名字(会自动加前缀)</param>
        /// <param name="cookieValue">cookie值</param>
        /// <param name="cookieExpireTime">过期时间（多少分钟之后过期）（单位：分钟）</param>
        public static void SetCookie(string cookieName, string cookieValue, int cookieExpireTime)
        {
            HttpCookie cookie = null;
            cookieName = preFix + cookieName;
            if ((cookie = HttpContext.Current.Request.Cookies[cookieName]) == null)
            {
                cookie = new HttpCookie(cookieName, StringHelper.UrlEncode(cookieValue));
            }

            cookie.Expires = DateTime.Now.AddMinutes(cookieExpireTime);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
        /// <summary>
        /// 给客户端设置一个已经准备好的cookie对象
        /// </summary>
        /// <param name="cookie"></param>
        public static void SetCookie(HttpCookie cookie)
        {
            HttpContext.Current.Response.AppendCookie(cookie);
        }
        /// <summary>
        /// 302重定向到某个地址，可以是虚拟路径。
        /// </summary>
        /// <param name="location"></param>
        public static void RedirectTo(string location)
        {
            HttpContext.Current.Response.Redirect(location);
        }
    }
}
